package test.excel.workbook;

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import test.excel.config.ColumnConfig;
import test.excel.config.SheetConfig;
import test.excel.dto.RowDto;
import test.excel.dto.SheetDto;

public class SheetReader {
    private Sheet sheet;

    private SheetConfig config;

    public SheetReader(Sheet sheet, SheetConfig config) {
        this.config = config;
        this.sheet = sheet;
    }

    public SheetDto read() {
        try {
            checkRowNum();

            int startPos = config.isHeader() ? config.getStartFrom() + 1 : config.getStartFrom();

            SheetDto sheetDto = new SheetDto(config.getTableName(), readColDefinitions());

            SheetHeader header = config.isHeader() ? new SheetHeaderReader().readHeader(sheet, config) : null;

            for (int r = startPos; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);

                if (row == null) continue;//empty row

                RowDto rowDto = new RowDto();

                for (ColumnConfig columnConfig : config.getColumns()) {
                    rowDto.getCells().add(new CellReader(row, columnConfig, header).read());
                }

                sheetDto.getRows().add(rowDto);
            }

            return sheetDto;
        } catch (Exception e) {
            throw new IllegalStateException("Exception when reading sheet " + config.getIndexOrSheetName(), e);
        }
    }

    private List<ColDefinition> readColDefinitions() {
        List<ColDefinition> colDefs = new ArrayList<ColDefinition>();

        for (ColumnConfig cc : config.getColumns()) {
            colDefs.add(new ColDefinition(cc.getTableColName(), cc.getType()));
        }

        return colDefs;
    }

    private void checkRowNum() {
        if (config.getStartFrom() > sheet.getLastRowNum()) throw new IllegalStateException("Last row num: " + sheet.getLastRowNum() + ", but start row is " + config.getStartFrom());
    }
}
